﻿using System;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using Config.Keede.Library;
using log4net;

namespace Keede.Rabbitmq.HandleService
{
    public partial class TaskHandleService : ServiceBase
    {
        readonly ILog _logger;
        TaskHandleController _taskHandleController;

        public TaskHandleService(TaskHandleController taskHandleController)
        {
            InitializeComponent();
            _logger = LogManager.GetLogger(typeof(TaskHandleService));
            _taskHandleController = taskHandleController;
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                _taskHandleController.Start();
                this._logger.Info("the service has been started.");
            }
            catch (Exception e)
            {
                this._logger.Error("start service error.", e);
            }
        }

        protected override void OnStop()
        {
            try
            {
                _taskHandleController?.Dispose();
                ApplicationStoped();
                this._logger.Info("the service has been stoped.");
            }
            catch (Exception e)
            {
                this._logger.Error("stop service error.", e);
            }
            base.OnStop();
        }

        protected override void OnShutdown()
        {
            try
            {
                _taskHandleController?.Dispose();
                ApplicationStoped();
                this._logger.Info("the service has been stoped.");
            }
            catch (Exception e)
            {
                this._logger.Error("stop service error.", e);
            }
            base.OnShutdown();
        }

        void ApplicationStoped()
        {
            var _conf = ConfigurationManager.GetSection("handleService") as HandleServiceConfig;
            if (string.IsNullOrEmpty(_conf?.ApplicationInit?.Assembly)) return;

            var types = Assembly.Load(_conf.ApplicationInit.Assembly).GetTypes().Where(w => w.BaseType != null && w.BaseType.Name == typeof(ApplicationInit).Name);
            foreach (var type in types)
            {
                var instance = Activator.CreateInstance(type) as ApplicationInit;
                instance?.OnApplicationStoped();
            }
        }
    }
}
